package com.feng.dt.quartz.job;

import com.feng.common.exception.ErrorCode;
import com.feng.common.exception.ValidationException;
import com.feng.common.spring.ApplicationContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * @author Lee
 */
public class ScheduleRunnable implements Runnable {

    private final static Logger LOGGER = LoggerFactory.getLogger(ScheduleRunnable.class);

    private Object target;
    private Method method;
    private String param;

    public ScheduleRunnable(String beanName, String methodName, String param) throws NoSuchMethodException {
        this.target = ApplicationContextHolder.getBean(beanName);
        if (!StringUtils.isEmpty(param)) {
            method = target.getClass().getDeclaredMethod(methodName,String.class);
        } else {
            method = target.getClass().getDeclaredMethod(methodName);
        }
        ReflectionUtils.makeAccessible(method);
        this.param = param;
    }

    @Override
    public void run() {
        if (!StringUtils.isEmpty(param)) {
            try {
                method.invoke(this.target,this.param);
            } catch (Exception e) {
                e.printStackTrace();
                String msg = String.format("执行调度任务失败，BeanName：[%s]，MethodName：[%s]，Param：[%s]",this.target.getClass().getName(),this.method.getName(),this.param);
                LOGGER.error(msg);
                throw new ValidationException(ErrorCode.SystemError,msg);
            }
        }
    }
}
